package com.stuffthathappens.concurrency.donut;

import com.stuffthathappens.concurrency.Donut;
import com.stuffthathappens.concurrency.SampleThreadFactory;

import javax.swing.*;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.awt.*;

/**
 * @author Eric M. Burke
 */
public class QueueSizePanel extends JPanel {
    private final BlockingQueue<Donut> queue;
    private JLabel sizeLabel = new JLabel("0");

    public QueueSizePanel(BlockingQueue<Donut> queue) {
        this.queue = queue;

        sizeLabel.setFont(new Font("Serif", Font.PLAIN, 36));
        add(sizeLabel);

        Executors.newSingleThreadScheduledExecutor(
                new SampleThreadFactory("queueSize"))
                .scheduleWithFixedDelay(new UpdateLabelRunnable(),
                        300, 300, TimeUnit.MILLISECONDS);
    }

    private class UpdateLabelRunnable implements Runnable {
        public void run() {
            final int size = queue.size();
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    sizeLabel.setText(Integer.toString(size));
                }
            });
            //To change body of implemented methods use File | Settings | File Templates.
        }
    }
}
